<?php

namespace app\admin\controller\iot\reservation;

use app\admin\service\UserService;
use app\BaseController;
use app\model\iot_model\IotDevice;
use app\model\iot_model\IotGrouping;
use app\model\iot_model\IotRoom;
use app\model\iot_model\IotRoomReservation;
use app\model\iot_model\IotRoomReservationBlacklist;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 存储缓存
     * @return bool|string
     */
    public function set(): bool|string
    {
        try {
            $param = $this->request->param();
            $key = 'iot_room_reservation'.$this->userData['unit_id'];
            cache($key,$param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取缓存
     * @return bool|string
     */
    public function get(): bool|string
    {
        try {
            $key = 'iot_room_reservation'.$this->userData['unit_id'];
            return success(cache($key));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 拉黑时长选择器
     * @return bool|string
     */
    public function blackoutDuration(): bool|string
    {
        $data = [
            ['time' => 3 * 24 * 60 * 60, 'day' => 3, 'name' => '三天'],
            ['time' => 7 * 24 * 60 * 60, 'day' => 7, 'name' => '七天'],
            ['time' => 30 * 24 * 60 * 60, 'day' => 30, 'name' => '三十天'],
            ['time' => 0, 'day' => 0, 'name' => '永久'],
        ];
        return success($data);
    }

    /**
     * 拉黑原因选择器
     * @return bool|string
     */
    public function blackReason(): bool|string
    {
        $data = [
            ['key' => 1, 'value' => '恶意发起咨询'],
            ['key' => 2, 'value' => '骂人'],
        ];
        return success($data);
    }

    /**
     * 功能室预约排行
     * @return bool|string
     */
    public function ranking(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $IotRoomModel = new IotRoom();
            $IotDeviceModel = new IotDevice();
            $data = $IotRoomModel->where($where)->with(['functionRoomName'])->withCount(['roomReservation'])->paginate($param['pageSize'])->toArray();
            $data['device'] = $IotDeviceModel->where($where)->count();
            $where[] = ['status','=',1];
            $data['room'] = $IotRoomModel->where($where)->count();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 功能室选项
     * @return bool|string
     */
    public function roomOption(): bool|string
    {
        try {
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $IotGroupingModel = new IotGrouping();
            $data = $IotGroupingModel->where($where)->with([
                'room' => function ($query) {
                    $query->with(['iotFunctionRoom'])->withCount(['iotDevice']);
                }
            ])->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 设置功能室开放时段
     * @return bool|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $IotRoomModel = new IotRoom();
            $info = $IotRoomModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $IotRoomReservationModel = new IotRoomReservation();
            $is_reservation = $IotRoomReservationModel->where([
                ['room_id','=',$param['id']],
                ['reserve_date','>=',date('Ymd')]
            ])->value('id');
            if ($is_reservation) throw new \Exception('已有人预约，无法编辑！');
            $info->save($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 月排班视图
     * @return bool|string
     */
    public function moonView(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
                'date|时间' => 'require',
            ]);
            $date_time = strtotime($param['date'] . '-01');
            $t = date('t', $date_time);
            $start_time = date('Ym01', $date_time);
            $end_time = date('Ym' . $t, $date_time);
            $dateData = custom_time([$start_time,$end_time]);

            $IotRoomReservationModel = new IotRoomReservation();
            $timeList = $IotRoomReservationModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['room_id','=',$param['id']],
                ['reserve_date','between',[$start_time,$end_time]],
                ['status','=',1]
            ])->with([
                'user'
            ])->select()->toArray();
            $UserService = new UserService($this->app);
            $departmentData = $UserService->getDepartmentAffiliationAll($this->userData['unit_id']);
            $timeData = [];
            foreach ($timeList as $v) {
                $v['department_name'] = $departmentData[$v['department_id']]['all_name'];
                $timeData[$v['reserve_date']][] = $v;
            }
            $data = [];
            foreach ($dateData as $item) {
                $dateTime = date('Ymd', strtotime($item['value']));
                $data[] = $timeData[$dateTime]??[];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预约详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $IotRoomReservationModel = new IotRoomReservation();
            $info = $IotRoomReservationModel->with([
                'user',
                'room' => function ($query) {
                    $query->with(['iotFunctionRoom']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $UserService = new UserService($this->app);
            $info['department_name'] = $UserService->getNotDelDepartmentName($this->userData['unit_id'],$info['department_id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑预约详情
     * @return bool|string
     */
    public function updateInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $IotRoomReservationModel = new IotRoomReservation();
            $info = $IotRoomReservationModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 加入黑名单
     * @return bool|string
     */
    public function addBlacklist(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'room_id|功能室' => 'require',
                'uid|用户' => 'require',
                'reason|移入原因' => 'require',
                'duration|拉黑时长' => 'require',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['operator_uid'] = $this->userData['id'];
            $param['time'] = time();
            $IotRoomReservationBlacklistModel = new IotRoomReservationBlacklist();
            $is_blacklist = $IotRoomReservationBlacklistModel->where([
                ['room_id','=',$param['room_id']],
                ['uid','=',$param['uid']],
            ])->value('id');
            if ($is_blacklist) throw new \Exception('不可重复拉黑！');
            $IotRoomReservationBlacklistModel->insert($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 黑名单
     * @return bool|string
     */
    public function blacklist(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|功能室' => 'require',
                'pageSize|每页显示数量' => 'require'
            ]);
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $where[] = ['room_id','=',$param['id']];
            $IotRoomReservationBlacklistModel = new IotRoomReservationBlacklist();
            $data = $IotRoomReservationBlacklistModel->where($where)->with([
                'user',
                'operator'
            ])->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除黑名单
     * @return bool|string
     */
    public function deleteBlacklist(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $IotRoomReservationBlacklistModel = new IotRoomReservationBlacklist();
            if (is_array($param['id'])) {
                $IotRoomReservationBlacklistModel->where('id','in',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $IotRoomReservationBlacklistModel->where('id','=',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}